package com.pinyoumei.app.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.pinyoumei.app.bean.WXAccessTokenInfo;
import com.pinyoumei.app.bean.WechatUserInfoBean;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.WXShare;
import com.pinyoumei.app.utils.event.WxLoginEvent;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.greenrobot.eventbus.EventBus;

/**
 * 微信分享接入类
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler{
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        WXShare share = new WXShare(this);
        api = share.getApi();
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try{
            if(!api.handleIntent(getIntent(), this)){
                finish();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent){
        super.onNewIntent(intent);

        setIntent(intent);
        if (!api.handleIntent(intent, this)){
            finish();
        }
    }



//    @Override
//    public void onResp(BaseResp baseResp){
//        Intent intent = new Intent(WXShare.ACTION_SHARE_RESPONSE);
//        intent.putExtra(WXShare.EXTRA_RESULT, new WXShare.Response(baseResp));
//        sendBroadcast(intent);
//        finish();
//    }




    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }
    }
    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            // 发送成功
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        //微信分享
                    Intent intent = new Intent(WXShare.ACTION_SHARE_RESPONSE);
                    intent.putExtra(WXShare.EXTRA_RESULT, new WXShare.Response(resp));
                    sendBroadcast(intent);
                    finish();
                        break;
                    case ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM:
                        WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
                        //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
                        String extraData =launchMiniProResp.extMsg;
                        EventBus.getDefault().post("wx_finsh");
                        finish();
                        break;

                	default:
                        // 获取code
                        String code = ((SendAuth.Resp) resp).code;
                        getAccessToken(code);
                		break;
                }

                break;
        }
    }







    /**
     * 获取授权口令
     */
    private void getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=wxfcdbc78aac617cee" +
                "&secret=d26408536b18f5eeb8eb7db041edd049" +
                "&code=" + code +
                "&grant_type=authorization_code";
        // 网络请求获取access_token
        OkGo.<String>get(url)
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);

                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WXAccessTokenInfo wxAccessTokenInfo = gson.fromJson(response.body(),WXAccessTokenInfo.class);

                        GetUserInfo(wxAccessTokenInfo.getAccess_token(),wxAccessTokenInfo.getOpenid());


                    }



                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }



                });
    }


    private void GetUserInfo(String access_token,String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" +access_token +
                "&openid=" +openid+
                "&lang=" + "zn_CN";
        // 网络请求获取access_token
        OkGo.<String>get(url)
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);

                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WechatUserInfoBean wechatUserInfoBean = gson.fromJson(response.body(), WechatUserInfoBean.class);

                        EventBusUtils.postSticky(new WxLoginEvent(wechatUserInfoBean.getOpenid(),wechatUserInfoBean.getNickname(),wechatUserInfoBean.getHeadimgurl()));

                        finish();
                    }



                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

                    }



                });
    }


}
